package controllers

import (
	"fmt"
	"myapp/dal/query"
	"myapp/pkg"
	"myapp/validates"
	"net/http"
	"strconv"
	"strings"

	"github.com/gin-gonic/gin"
	"gorm.io/gorm"
)

func HomeHandler(db *gorm.DB) gin.HandlerFunc {
	return func(c *gin.Context) {
		query.SetDefault(db)

		query.Banner.CreatedAt.DateFormat("%W %M %Y")
		banners, _, _ := query.Banner.Where(query.Banner.Status.Eq(1)).Order(query.Banner.Displayorder.Desc()).FindByPage(0, 4)

		query.Need.CreatedAt.DateFormat("%W %M %Y")
		needs, _, _ := query.Need.Where(query.Need.Status.Eq(1), query.Need.IsTop.Eq(1)).Order(query.Need.ID.Desc()).FindByPage(0, 20)

		// 将查询结果转换为自定义结构体
		var customNeeds []validates.Need
		for _, need := range needs {
			customNeeds = append(customNeeds, validates.ProcessNeed(need))
		}

		c.JSON(http.StatusOK, gin.H{"code": 0, "data": gin.H{
			"banners": banners,
			"needs":   customNeeds,
		}})
	}
}

func NeedCategoriesHandler(db *gorm.DB) gin.HandlerFunc {
	return func(c *gin.Context) {
		query.SetDefault(db)

		categories, _, _ := query.Category.Where().FindByPage(0, 100)

		c.JSON(http.StatusOK, gin.H{"code": 0, "data": gin.H{
			"categories": categories,
		}})
	}
}

func NeedListHandler(db *gorm.DB) gin.HandlerFunc {
	return func(c *gin.Context) {
		query.SetDefault(db)

		locale, _ := c.GetQuery("locale")
		category_id, _ := c.GetQuery("category_id")
		keyword, _ := c.GetQuery("keyword")
		typestr, _ := c.GetQuery("type")
		typestr1, _ := strconv.Atoi(typestr)

		pagestr, _ := c.GetQuery("page")
		page1, _ := strconv.Atoi(pagestr)
		if page1 <= 1 {
			page1 = 1
		}

		pagestr_news, _ := c.GetQuery("page_news")
		page2, _ := strconv.Atoi(pagestr_news)
		if page2 <= 1 {
			page2 = 1
		}

		query.Need.CreatedAt.DateFormat("%W %M %Y")

		querys := query.Need.Where(query.Need.Status.Eq(1))
		if len(category_id) > 0 {
			category_ids := strings.Split(category_id, ",")
			sizeCondition := query.Need.Where(query.Need.CategoryIds.FindInSetWith(category_ids[0]))
			for _, cc := range category_ids[1:] {
				sizeCondition = sizeCondition.Or(query.Need.CategoryIds.FindInSetWith(cc))
			}
			querys = querys.Where(sizeCondition)
			//querys = querys.Where(query.Need.CategoryIds.FindInSet(category_id))
		}

		if len(keyword) > 0 {
			if locale == "en_US" {
				querys = querys.Where(query.Need.TitleEn.Like("%" + keyword + "%"))
			} else {
				querys = querys.Where(query.Need.Title.Like("%" + keyword + "%"))
			}
		}

		if len(typestr) > 0 {
			querys = querys.Where(query.Need.Type.Eq(int32(typestr1)))
		}

		offset := (page1 - 1) * 10
		needs, _, _ := querys.Order(query.Need.IsTop.Desc(), query.Need.ID.Desc()).FindByPage(offset, 10)

		// 将查询结果转换为自定义结构体
		var customNeeds []validates.Need
		for _, need := range needs {
			customNeeds = append(customNeeds, validates.ProcessNeed(need))
		}

		query.Banner.CreatedAt.DateFormat("%W %M %Y")
		banners, _, _ := query.Banner.Where(query.Banner.Status.Eq(1)).Order(query.Banner.Displayorder.Desc()).FindByPage(0, 5)

		query.Article.CreatedAt.DateFormat("%W %M %Y")
		offset2 := (page2 - 1) * 2
		news, _, _ := query.Article.Where(query.Article.IsSwitch.Eq(1), query.Article.Type.Eq(1)).Order(query.Article.IsTop.Desc(), query.Article.ID.Desc()).FindByPage(offset2, 2)
		var customArticles []validates.Article
		for _, article := range news {
			customArticles = append(customArticles, validates.ProcessArticle(article))
		}

		c.JSON(http.StatusOK, gin.H{"code": 0, "data": gin.H{
			"news":    customArticles,
			"banners": banners,
			"needs":   customNeeds,
		}})
	}
}

func NeedViewHandler(db *gorm.DB) gin.HandlerFunc {
	return func(c *gin.Context) {
		query.SetDefault(db)

		id, _ := strconv.Atoi(c.Param("id"))

		query.Need.CreatedAt.DateFormat("%W %M %Y")
		needs, _ := query.Need.Where(query.Need.ID.Eq(int32(id))).Take()

		userId, _ := c.Get("userID")
		is_interested := false
		if v, ok := userId.(uint); ok {
			count, _ := query.Join.Where(query.Join.NeedID.Eq(int32(id)), query.Join.Type.Eq(0), query.Join.UserID.Eq(int32(v))).Count()
			if count > 0 {
				is_interested = true
			}
		}

		c.JSON(http.StatusOK, gin.H{"code": 0, "data": gin.H{
			"needs":         validates.ProcessNeed(needs),
			"is_interested": is_interested,
		}})
	}
}

func MemberCategoriesHandler(db *gorm.DB) gin.HandlerFunc {
	return func(c *gin.Context) {
		query.SetDefault(db)

		categories, _, _ := query.MemberCategory.Where(query.MemberCategory.Pid.Neq(0)).Order(query.MemberCategory.ID.Asc()).FindByPage(0, 1000)
		for _, v := range categories {
			categoryp, _ := query.MemberCategory.Where(query.MemberCategory.ID.Eq(v.Pid)).Take()
			v.Name = categoryp.Name + "：" + v.Name
			v.NameEn = categoryp.NameEn + "：" + v.NameEn
		}

		c.JSON(http.StatusOK, gin.H{"code": 0, "data": gin.H{
			"categories": categories,
		}})
	}
}

func MemberListHandler(db *gorm.DB) gin.HandlerFunc {
	return func(c *gin.Context) {
		query.SetDefault(db)

		locale, _ := c.GetQuery("locale")
		category_id, _ := c.GetQuery("category_id")
		keyword, _ := c.GetQuery("keyword")

		pagestr, _ := c.GetQuery("page")
		page1, _ := strconv.Atoi(pagestr)
		if page1 <= 1 {
			page1 = 1
		}

		query.Member.CreatedAt.DateFormat("%W %M %Y")

		querys := query.Member.Where()
		if len(category_id) > 0 {
			querys = querys.Where(query.Member.MemberCategoryIds.FindInSetWith(category_id))
		}

		if len(keyword) > 0 {
			if locale == "en_US" {
				querys = querys.Where(query.Member.NameEn.Like("%" + keyword + "%"))
			} else {
				querys = querys.Where(query.Member.Name.Like("%" + keyword + "%"))
			}
		}

		offset := (page1 - 1) * 10
		needs, _, _ := querys.Order(query.Member.ID.Asc()).FindByPage(offset, 10)

		// 将查询结果转换为自定义结构体
		var customNeeds []validates.Member
		for _, need := range needs {
			customNeeds = append(customNeeds, validates.ProcessMember(need))
		}

		c.JSON(http.StatusOK, gin.H{"code": 0, "data": gin.H{
			"needs": customNeeds,
		}})
	}
}

func BannerViewHandler(db *gorm.DB) gin.HandlerFunc {
	return func(c *gin.Context) {
		query.SetDefault(db)

		id, _ := strconv.Atoi(c.Param("id"))

		banner, _ := query.Banner.Where(query.Banner.ID.Eq(int32(id))).Take()
		banner.Intro = strings.ReplaceAll(banner.Intro, "/uploads", "https://miniapp.gzqxasa.cn/uploads")
		banner.IntroEn = strings.ReplaceAll(banner.IntroEn, "/uploads", "https://miniapp.gzqxasa.cn/uploads")

		c.JSON(http.StatusOK, gin.H{"code": 0, "data": gin.H{
			"banner": banner,
		}})
	}
}

func TransHandler(db *gorm.DB) gin.HandlerFunc {
	return func(c *gin.Context) {
		query.SetDefault(db)

		queryStr := c.PostForm("string")

		// 执行翻译
		result, err := pkg.Translate(queryStr)
		if err != nil {
			fmt.Println("Error:", err)
			return
		}

		c.JSON(http.StatusOK, gin.H{"code": 0, "data": result})
	}
}

func TransMemberHandler(db *gorm.DB) gin.HandlerFunc {
	return func(c *gin.Context) {
		query.SetDefault(db)

		/*queryStr := c.PostForm("string")

		// 执行翻译
		result, err := pkg.Translate(queryStr)
		if err != nil {
			fmt.Println("Error:", err)
			return
		}

		// 打印翻译结果
		fmt.Println("翻译结果:", result)*/

		rs1, _, err := query.MemberCategory.Where().FindByPage(0, 10000)
		if err != nil {
			fmt.Println(err)
		}

		var cat_querys []string
		for _, v := range rs1 {
			//fmt.Println(v.ID, v.Name, v.Desc)
			if len(v.Name) > 0 && v.NameEn == "" {
				cat_querys = append(cat_querys, v.Name)
			}
		}

		if len(cat_querys) > 0 {
			queryStr := strings.Join(cat_querys, "\n")

			// 执行翻译
			result, err := pkg.Translate(queryStr)
			if err != nil {
				fmt.Println("Error:", err)
				return
			}

			// 打印翻译结果
			fmt.Println("翻译结果:", result)

			for k, v := range result.TransResult {
				fmt.Println(k, v.Src, v.Dst)
				query.MemberCategory.Where(query.MemberCategory.Name.Eq(v.Src)).UpdateColumn(query.MemberCategory.NameEn, v.Dst)
			}

		}

		rs, _, err := query.Member.Where().FindByPage(0, 100000)
		if err != nil {
			fmt.Println(err)
		}

		var querys []string
		var querys1 []string
		for _, v := range rs {
			//fmt.Println(v.ID, v.Name, v.Desc)
			if len(v.Name) > 0 && v.NameEn == "" {
				querys = append(querys, v.Name)
			}
			if len(v.Services) > 0 && v.ServicesEn == "" {
				querys1 = append(querys1, v.Services)
			}
			if len(v.Content) > 0 && v.ContentEn == "" {
				//querys1 = append(querys1, v.Content)

				// 执行翻译
				result, err := pkg.Translate(v.Content)
				if err != nil {
					fmt.Println("Error:", err)
					return
				}

				// 打印翻译结果
				fmt.Println("翻译结果:", result)

				for k, v := range result.TransResult {
					fmt.Println(k, v.Src, v.Dst)
					query.Member.Where(query.Member.Content.Eq(v.Src)).UpdateColumn(query.Member.ContentEn, v.Dst)
				}
			}
		}

		if len(querys) > 0 {
			queryStr := strings.Join(querys, "\n")

			// 执行翻译
			result, err := pkg.Translate(queryStr)
			if err != nil {
				fmt.Println("Error:", err)
				return
			}

			// 打印翻译结果
			fmt.Println("翻译结果:", result)

			for k, v := range result.TransResult {
				fmt.Println(k, v.Src, v.Dst)
				query.Member.Where(query.Member.Name.Eq(v.Src)).UpdateColumn(query.Member.NameEn, v.Dst)
			}

		}

		if len(querys1) > 0 {
			queryStr := strings.Join(querys1, "\n")

			// 执行翻译
			result, err := pkg.Translate(queryStr)
			if err != nil {
				fmt.Println("Error:", err)
				return
			}

			// 打印翻译结果
			fmt.Println("翻译结果:", result)

			for k, v := range result.TransResult {
				fmt.Println(k, v.Src, v.Dst)
				query.Member.Where(query.Member.Services.Eq(v.Src)).UpdateColumn(query.Member.ServicesEn, v.Dst)
			}

		}

		c.JSON(http.StatusOK, gin.H{"code": 0, "data": "操作成功"})
	}
}

func ArticleViewHandler(db *gorm.DB) gin.HandlerFunc {
	return func(c *gin.Context) {
		query.SetDefault(db)

		id, _ := strconv.Atoi(c.Param("id"))

		article, _ := query.Article.Where(query.Article.ID.Eq(int32(id))).Take()
		article.Content = strings.ReplaceAll(article.Content, "/uploads", "https://miniapp.gzqxasa.cn/uploads")
		article.ContentEn = strings.ReplaceAll(article.ContentEn, "/uploads", "https://miniapp.gzqxasa.cn/uploads")

		c.JSON(http.StatusOK, gin.H{"code": 0, "data": gin.H{
			"article": article,
		}})
	}
}

func MemberViewHandler(db *gorm.DB) gin.HandlerFunc {
	return func(c *gin.Context) {
		query.SetDefault(db)

		id, _ := strconv.Atoi(c.Param("id"))

		needs, _ := query.Member.Where(query.Member.ID.Eq(int32(id))).Take()

		userId, _ := c.Get("userID")
		is_interested := false
		if v, ok := userId.(uint); ok {
			count, _ := query.Join.Where(query.Join.NeedID.Eq(int32(id)), query.Join.Type.Eq(1), query.Join.UserID.Eq(int32(v))).Count()
			if count > 0 {
				is_interested = true
			}
		}

		c.JSON(http.StatusOK, gin.H{"code": 0, "data": gin.H{
			"needs":         validates.ProcessMember(needs),
			"is_interested": is_interested,
		}})
	}
}
